package models

import (
	"SlowAdmin/pkg/utils"
	"fmt"
	"github.com/astaxie/beego"
	"gorm.io/gorm"
)

type File struct {
	gorm.Model
	GroupId  uint   `json:"group_id"`
	Storage  string `json:"storage"`
	Domain   string `json:"domain"`
	FileName string `json:"file_name"`
	FileType int    `json:"file_type"`
	FilePath string `json:"file_path"`
	FileSize int    `json:"file_size"`
	FileExt  string `json:"file_ext"`
}

const FILE_TYPE_IMAGE = 1
const FILE_TYPE_VIDEO = 2
const FILE_TYPE_ANNEX = 3

func (f *File) GetFileType(fileType string) int {
	switch fileType {
	case "image":
		return FILE_TYPE_IMAGE
	case "video":
		return FILE_TYPE_VIDEO
	default:
		return FILE_TYPE_ANNEX
	}
}

// @title 新增
func (f *File) Store() error {
	return Db.Create(f).Error
}

func (f *File) GetList(page, pageSize int, fileType, keyword string) ([]map[string]interface{}, int64) {
	var list []map[string]interface{}
	var count int64

	Db.Model(f).Count(&count)
	Db.Model(File{}).
		Order("created_at desc").
		Limit(pageSize).
		Offset((page-1)*pageSize).
		Where("file_type = ?", f.GetFileType(fileType)).
		Where("file_name like ?", fmt.Sprintf("%%%s%%", keyword)).
		Select([]string{"id", "group_id", "storage", "domain", "file_name", "file_path", "file_size"}).
		Find(&list)

	for _, item := range list {
		if item["storage"] == "local" {
			item["file_path"] = fmt.Sprintf("%s/%s", beego.AppConfig.String("app_url"), item["file_path"])
		} else {
			item["file_path"] = fmt.Sprintf("%s/%s", item["domain"], item["file_path"])
		}

		item["file_size"] = utils.FormatFileSize(item["file_size"].(int))
	}

	return list, count
}
